package com.example.business;

import com.example.data.mapper.RecordsMapper;
import com.example.data.model.Records;
import com.example.page.Page;
import com.example.page.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by hldev on 17-2-9.
 */
@Service
public class RecordsService {

    @Autowired
    private RecordsMapper recordsMapper;

    public Records findOne(Integer id) {
        return recordsMapper.findOne(id);
    }

    public List<Records> findAll() {
        return recordsMapper.findAll();
    }

    public void createRecords(Records records) {
        recordsMapper.createRecords(records);
    }

    public Page<Records> findPage(Pageable pageable, Integer parentRecordId, Integer parentCreateBy, Integer status, String title, String createName, String beginDate, String endDate) {
        pageable.addSomeParam("parentRecordId", parentRecordId)
                .addSomeParam("parentCreateBy", parentCreateBy)
                .addSomeParam("status", status)
                .addSomeParam("title", title)
                .addSomeParam("createName", createName)
                .addSomeParam("beginDate", beginDate)
                .addSomeParam("endDate", endDate);

        List<Records> list = recordsMapper.findPage(pageable)
                .stream()
                .map(Records -> {
                    Records.setContent(clearText(Records.getContent()));
                    return Records;
                })
                .collect(Collectors.toList());
        return new Page<>(pageable, list);
    }

    private String clearText(String content) {
        if (StringUtils.isBlank(content))
            return "";

        return content.replaceAll("\\\\r\\\\n", "");
    }

    @Transactional
    public void setStatus(Records records) {
        recordsMapper.setStatus(records);
    }

    public void deleteRecords(Integer id) {
        recordsMapper.delete(id);
    }
}
